//
//  BinaryTree_traverse.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/13.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

extension BinaryTree {
    
    public enum TraverseOrder {
        case pre
        case `in`
        case post
        case level
    }
    
    public func forEach(_ order: TraverseOrder, _ body: (Element) throws -> Void) rethrows {
        switch order {
        case .pre: try travPre(body)
        case .in: try travIn(body)
        case .post: try travPost(body)
        case .level: try travLevel(body) }
    }
    
    /// 层次遍历
    public func travLevel(_ body: (Element) throws -> Void) rethrows {
        guard let root = root else { return }
        try root.travLevel(body)
    }
    
    /// 先序遍历
    public func travPre(_ body: (Element) throws -> Void) rethrows {
        guard let root = root else { return }
        try root.travPre(body)
    }
    
    /// 中序遍历
    public func travIn(_ body: (Element) throws -> Void) rethrows {
        guard let root = root else { return }
        try root.travIn(body)
    }
    
    /// 后序遍历
    public func travPost(_ body: (Element) throws -> Void) rethrows {
        guard let root = root else { return }
        try root.travPost(body)
    }
}
